package club.pinea.handler.game;

import club.pinea.annotations.Head;
import club.pinea.interfaces.TCPMessage;
import club.pinea.mapper.RoomMapper;
import club.pinea.model.Room;
import club.pinea.proto.BasicProto;
import club.pinea.proto.CommandProto;
import club.pinea.proto.GameProto;
import club.pinea.send.MessageSend;
import club.pinea.service.RedisService;
import club.pinea.service.UserService;
import club.pinea.session.GlobalServerPlayerContainer;
import club.pinea.session.IOSession;
import club.pinea.session.ServerPlayer;
import club.pinea.util.GameUtil;
import club.pinea.utils.RedisCache;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Head(CommandProto.Command.C_S_GET_CARD_VALUE)
public class GetCardHandler implements TCPMessage<BasicProto.BaseMessage> {

    @Resource
    private RoomMapper roomMapper;

    @Value("${server.game.maxScore}")
    public Integer maxScore;

    @Resource
    private UserService userService;

    @Resource
    private RedisService redisService;

    @Override
    public void doMessage(BasicProto.BaseMessage msg, IOSession session) throws Exception {
        ServerPlayer serverPlayer = GlobalServerPlayerContainer.getServerPlayer(session);
//        serverPlayer.setDoubleTime(1);
        GameProto.GetCardRequest request = GameProto.GetCardRequest.parseFrom(msg.getBody());
        Room room = roomMapper.queryById(serverPlayer.getRoom());
        int score = request.getScore();
//        multiplyPower = selectMutiplyPower(seatId);

//        this.score = obj.getInteger("score");//同步初始分数
        if (score > maxScore) {
            throw new IllegalArgumentException("参数错误，分数超过最大押分限制");
        }
//		else if(score<GameUtil.minScore){
//			throw new IllegalArgumentException("参数错误，分数不满足最小押分需求");
//		}
        if (score > userService.getUserMoneyById(serverPlayer.getUserId())) {
            throw new IllegalArgumentException("发牌失败，您的余额不足！");
        }

        //获取需要发送到串口的数据
        Integer seatId = redisService.getSeatsInfo(serverPlayer.getUser().getUsername(), serverPlayer.getSeatId(), serverPlayer.getRoom());
        if (seatId == null) {
            throw new IllegalArgumentException("参数错误，您的座位信息异常，您未在当前座位！");
        }
//        byte[] request = request = requestUtil.createRequestMessage(userId, roomId, seatId, score, this);
//        //获取串口的数据，返回牌的类型与比倍的结果，同时更新用户信息表中的payscore字段
////		cardMessage = SerialPortSession.getCardMessage(request, userId, roomId, seatId,score);//发送数据并等待返回数据
//
//        cardMessage = handler.sendMessage(request, userId, roomId, seatId, score);

//        int type = CardUtil.selectCardTypeByPower(cardMessage[0]);
        int type = (int) (Math.random() * 5) + 6;

        GameUtil game = new GameUtil(type, score);
        serverPlayer.setGameUtil(game);
//        logger.info("客户端" + clientIP + "【userName:" + userName + "】" + "生成牌" + game.getCardsList().toString() + ",牌型为：" + type);
//        service.updateMoney(-1.0 * score / multiplyPower, userId);
//        obj = new JSONObject();
//        if (this.addScoreLogic) {
//            //当现在需要增加奖池的分数的时候
//            int[] result = redisService.addPoolScores(poolScore, seatId);
//            obj.put("bonus", result);
//            this.addScoreLogic = !this.addScoreLogic;
//        }
        GameProto.GetCardResponse response = GameProto.GetCardResponse.newBuilder()
                .setDouble(room.getMultiplyPower())
                .setRes(MessageSend.successRes())
                .addAllCards(game.getNowCardList())
                .build();
        MessageSend.sendToUser(response, session);
    }
}
